package com.caiheng.api.service.platfom.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.caiheng.api.dao.platform.ParameterMapper;
import com.caiheng.api.entity.platform.Parameter;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.platfom.ParameterService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ParameterServiceImpl extends BaseServiceImpl<ParameterMapper, Parameter> implements ParameterService {

    @Resource
    private ParameterMapper parameterMapper;
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @Override
    public Parameter getParameterById(int id) {
        Parameter parameter = null;
        String key = "parameter_" + id;
        boolean blHasKey = redisTemplate.opsForHash().hasKey(key,key);
        if (blHasKey) {
            Object object = redisTemplate.opsForHash().get(key, key);
            String itemDicts = object != null ? object.toString() : "";
            if (StrUtil.isNotEmpty(itemDicts)) {
                JSONObject jsonObject = JSONUtil.parseObj(itemDicts);
                parameter = JSONUtil.toBean(JSONUtil.toJsonStr(jsonObject), Parameter.class);
            } else {
                parameter = parameterMapper.selectOneByColumn("is_default",1);
                redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(parameter));
            }
        } else {
            parameter = parameterMapper.selectOneByColumn("is_default",1);
            redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(parameter));
        }
        return parameter;
    }

    @Override
    public void resetParameter(int id) {
        String key = "parameter_" + id;
        Parameter parameter = parameterMapper.selectOneByColumn("is_default",1);
        redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(parameter));
    }


}
